<?php

namespace app\api\Service;

use fast\Http;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;
use app\common\library\Auth;
use app\common\library\Sms;

class ThirdService
{
    // 获取Openid
    public static function wechat_login($data)
    {
        $auth = Auth::instance();
        $code = $data['code'];
        if(!$code) return ['code'=>0,'msg'=>'无效的请求!','data'=>''];
        // return ['code'=>0,'msg'=>$code];
        // 获取openid和access_token
        $app_id = Config::get('site.appid');
        $app_secret = Config::get('site.secret');
        // 发送请求，获取用户openid和access_token
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$app_id}&secret={$app_secret}&code={$code}&grant_type=authorization_code";
        $data = Http::get($url);
//        $data = '{"access_token":"82_2XOocR7RP4O2auESRpDokPz3DQdRe1Y_fTLJZvR2ySbyX1B9RfAdE4nGgCnxTrvBTqdJL7a5AB0-GI_uvwEuWwNLu0p4dvJ063drUq_QloE","expires_in":7200,"refresh_token":"82_wZfSfoJG6ccFdeh9eHl83U4trgvb2m1d_t6hhOdTnMiHOUsGUHQag5yURiMiGm0S2xa65a_4BYy9DJ4mX6dtpLwif5splcom4aWeJ9KUiWI","openid":"o4A1K6tpCAKDjzZqqXtQRKHCdSCM","scope":"snsapi_userinfo","unionid":"oh7i06jaTq_g07Td3XufjcCbeefU"}';
        $data = json_decode($data);
//        return $data;
        // 防止第二次访问动态链接报错
        // 判断是否获取到当前用户的openid

        if (isset($data->openid)) {
            $open_id = $data->openid;
            $access_token = $data->access_token;
            // 获取当前用户信息
            $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $open_id . '&lang=zh_CN';
            $user_info = Http::get($url);
//            $user_info = '{"openid":"o4A1K6tpCAKDjzZqqXtQRKHCdSCM","nickname":"小许许可证","sex":0,"language":"","city":"","province":"","country":"","headimgurl":"https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/VztmaOm4apmGwnxnRZicJPpmD9kdEKskQjiazSHNRlmP5G2Rv9sUwlhZgUZUAibXibWt4pSxiaAjYehOs9HIfcXtAYg\/132","privilege":[],"unionid":"oh7i06jaTq_g07Td3XufjcCbeefU"}';
            $user_info = json_decode($user_info);
            // 取出用户信息
            /*
            *user_openid :用户openId
            *user_nickname :用户昵称
            *user_sex :性别
            *user_province :省
            *user_city :城市
            *user_headimgurl :用户头像url
            *user_unionid :绑定开放平台后才有这个字段
            */
            $user_openid = $user_info->openid;
            $user_nickname = $user_info->nickname;
            $user_headimgurl = $user_info->headimgurl;
            // $user_unionid = $user_info->unionid;
            // 判断用户是否存在
            $userInfo = \app\admin\model\User::where(['openid' => $user_openid])->find();

            if (empty($userInfo)) {
                //用户不存在，提示绑定
                $insert['nickname'] = $user_nickname;
                $insert['avatar'] = $user_headimgurl;
                $insert['openid'] = $user_openid;
                $insert['is_bind'] = 0;// 是否绑定 1是 0否
                // $insert['unionid'] = $user_unionid;
                // $insert['create_time'] = time();
                // $userId = Db::name('qt_users')->insertGetId($insert);

                return ['code'=>1,'msg'=>'请先绑定手机号','data'=>$insert];

            }else {
                //用户已经存在进行登录操作或者进行用户下一步数据绑定和认证等

                $res = $auth->direct($userInfo->id);
                if( !$res ){
                    return ['code' => 0, 'msg' => '登录失败','data'=>''];
                }
                $userInfo = $auth->getUserinfo();
                $userInfo['is_bind'] = 1;// 是否绑定 1是 0否

                return ['code' => 1,'msg' => '登录成功','data' => $userInfo];
            }
        }else{
            return ['code'=>0,'msg'=>$data->errmsg,'data'=>''];
//            return ['code'=>0,'msg'=>'无效的请求','data'=>''];
        }


    }

    // 绑定手机号
    public static function bind_mobile($data){
        $auth = Auth::instance();
        try{
            if (isset($data['password']) && isset($data['confirmpw']) && $data['password'] != $data['confirmpw']) {
                return ['code'=>0,'msg'=>'两次密码不一致','data'=>''];
            }

            // 判断手机号格式
            if (isset($data['mobile']) && !Validate::regex($data['mobile'], "^1\d{10}$")) {
                return ['code'=>0,'msg'=>'手机号格式不对','data'=>''];
            }

            //判断验证码是否正确
            if (!Sms::check($data['mobile'], $data['code'], 'wechatbind')) {
                return ['code'=>0,'msg'=>'验证码错误','data'=>''];
            }

            //判断手机号是否已注册
            $user = \app\admin\model\User::where(['mobile'=>$data['mobile']])->field(['id','openid','mobile',
                'nickname','avatar','status'])->find();
            if( !$user ){
                $salt = Random::alnum();
                $user = \app\admin\model\User::create([
                    'username' => $data['mobile'],
                    'nickname' => $data['nickname'],
                    'mobile' => $data['mobile'],
                    'avatar' => $data['avatar'],
                    'openid' => $data['openid'],
                    'password' => $auth->getEncryptPassword($data['mobile'], $salt),
                    'salt' => $salt,
                ]);

                // 判断是否有邀请码
                if( isset($data['invite']) && $data['invite'] ) {
                    $invite = $data['invite'];
                    if($invite){
                        $firstChar = substr($invite, 0, 1);
                        if($firstChar == 'U'){
                            $pid = substr($invite, 1);
                        }
                        if($firstChar == 'S'){
                            $pid = 0;
                        }
                    }
                    // 保存父级
                    $user->pid = $pid;
                    $user->save();
                    // 邀请人奖励优惠券
                    $res = userInviteReward($pid);
//                    return $res;
                }
            }else{
                return ['code' => 0, 'msg' => '手机号已注册','data'=>''];
            }

            if( isset($user->status) && $user->status == 'hidden' ){
                return ['code' => 0, 'msg' => '账号已被禁用','data'=>''];
            }

            $res = $auth->direct($user->id);
            if( !$res ){
                return ['code' => 0, 'msg' => '登录失败','data'=>''];
            }
            $userinfo = $auth->getUserInfo();

            Db::commit();
        }catch(\Exception $e){
            Db::rollback();
            return ['code'=>0,'msg'=>$e->getMessage(),'data'=>''];
        }

        return [
            'code' => 1,
            'msg' => '登录成功',
            'data' => $userinfo
        ];
    }

    // 绑定微信
    public static function bind_wechat($data)
    {

        $code = $data['code'];
        $auth = Auth::instance();
        $user_id = $auth->id;
        if(!$code) return ['code'=>0,'msg'=>'无效的请求!','data'=>''];
        // 获取openid和access_token
        $config = self::getByDefault('wechat');
        $app_id = Config::get('site.appid');
        $app_secret = Config::get('site.secret');
        // 发送请求，获取用户openid和access_token
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $app_id . '&secret=' . $app_secret . '&code=' . $code . '&grant_type=authorization_code';
        $data = Http::get($url);
        $data = json_decode($data);
        // 防止第二次访问动态链接报错
        // 判断是否获取到当前用户的openid
        // $data['openid'] = 'ow41r6zbQzeyAp9tZzfO8jvsyUAY';

        if (isset($data['openid'])) {
            $open_id = $data['openid'];
            // 获取当前用户信息

            User::where(['id'=>$user_id])->update(['openid'=>$open_id]);

            return ['code' => 1,'msg' => '绑定成功','data'=>''];

        }else{
            return ['code'=>0,'msg'=>'无效的请求','data'=>''];
        }


    }

}
